<template>
  <div 
    ref="containerRef"
    class="dv-border-box" 
    :class="[`border-box-${variant}`, `border-type-${normalizedType}`, { 'is-dark': isDark, 'reverse': reverse }]"
    :style="{ 
      width: props.width ? (typeof props.width === 'number' ? `${props.width}px` : props.width) : '100%',
      height: props.height ? (typeof props.height === 'number' ? `${props.height}px` : props.height) : '100%'
    }"
  >
    <!-- 扫描线效果 -->
    <div class="scan-line" v-if="isDark && normalizedType === 'default'"></div>
    
    <!-- 背景网格 -->
    <div class="bg-grid" v-if="isDark && normalizedType === 'default'"></div>
    
    <!-- 默认样式 SVG -->
    <svg v-if="normalizedType === 'default'" class="border-svg" :width="width" :height="height">
      <defs>
        <!-- 发光滤镜 -->
        <filter :id="`glow-${uid}`">
          <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
          <feMerge>
            <feMergeNode in="coloredBlur"/>
            <feMergeNode in="SourceGraphic"/>
          </feMerge>
        </filter>
        
        <!-- 渐变定义 -->
        <linearGradient :id="`grad-${uid}`" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" :style="`stop-color:var(--border-color);stop-opacity:0`" />
          <stop offset="50%" :style="`stop-color:var(--border-color);stop-opacity:1`" />
          <stop offset="100%" :style="`stop-color:var(--border-color);stop-opacity:0`" />
        </linearGradient>
      </defs>
      
      <!-- 四个角的装饰 - 增强版 -->
      <g class="corner-group corner-lt-group">
        <polyline
          class="corner-lt corner-main"
          :points="`0,${cornerSize} 0,0 ${cornerSize},0`"
          :filter="isDark ? `url(#glow-${uid})` : ''"
        />
        <polyline
          class="corner-lt corner-inner"
          :points="`3,${cornerSize - 5} 3,3 ${cornerSize - 5},3`"
        />
        <circle class="corner-dot" cx="0" cy="0" r="2">
          <animate attributeName="r" values="2;4;2" dur="2s" repeatCount="indefinite" />
        </circle>
      </g>
      
      <g class="corner-group corner-rt-group">
        <polyline
          class="corner-rt corner-main"
          :points="`${width - cornerSize},0 ${width},0 ${width},${cornerSize}`"
          :filter="isDark ? `url(#glow-${uid})` : ''"
        />
        <polyline
          class="corner-rt corner-inner"
          :points="`${width - cornerSize + 5},3 ${width - 3},3 ${width - 3},${cornerSize - 5}`"
        />
        <circle class="corner-dot" :cx="width" cy="0" r="2">
          <animate attributeName="r" values="2;4;2" dur="2s" begin="0.5s" repeatCount="indefinite" />
        </circle>
      </g>
      
      <g class="corner-group corner-lb-group">
        <polyline
          class="corner-lb corner-main"
          :points="`0,${height - cornerSize} 0,${height} ${cornerSize},${height}`"
          :filter="isDark ? `url(#glow-${uid})` : ''"
        />
        <polyline
          class="corner-lb corner-inner"
          :points="`3,${height - cornerSize + 5} 3,${height - 3} ${cornerSize - 5},${height - 3}`"
        />
        <circle class="corner-dot" cx="0" :cy="height" r="2">
          <animate attributeName="r" values="2;4;2" dur="2s" begin="1s" repeatCount="indefinite" />
        </circle>
      </g>
      
      <g class="corner-group corner-rb-group">
        <polyline
          class="corner-rb corner-main"
          :points="`${width - cornerSize},${height} ${width},${height} ${width},${height - cornerSize}`"
          :filter="isDark ? `url(#glow-${uid})` : ''"
        />
        <polyline
          class="corner-rb corner-inner"
          :points="`${width - cornerSize + 5},${height - 3} ${width - 3},${height - 3} ${width - 3},${height - cornerSize + 5}`"
        />
        <circle class="corner-dot" :cx="width" :cy="height" r="2">
          <animate attributeName="r" values="2;4;2" dur="2s" begin="1.5s" repeatCount="indefinite" />
        </circle>
      </g>
      
      <!-- 边框线条 - 带动画 -->
      <g v-if="showBorder">
        <!-- 顶部边框 -->
        <line
          class="border-line border-top"
          :x1="cornerSize"
          y1="0"
          :x2="width - cornerSize"
          y2="0"
          stroke-dasharray="5,5"
        >
          <animate attributeName="stroke-dashoffset" from="0" to="10" dur="1s" repeatCount="indefinite" />
        </line>
        
        <!-- 右侧边框 -->
        <line
          class="border-line border-right"
          :x1="width"
          :y1="cornerSize"
          :x2="width"
          :y2="height - cornerSize"
          stroke-dasharray="5,5"
        >
          <animate attributeName="stroke-dashoffset" from="0" to="10" dur="1s" repeatCount="indefinite" />
        </line>
        
        <!-- 底部边框 -->
        <line
          class="border-line border-bottom"
          :x1="cornerSize"
          :y1="height"
          :x2="width - cornerSize"
          :y2="height"
          stroke-dasharray="5,5"
        >
          <animate attributeName="stroke-dashoffset" from="0" to="10" dur="1s" repeatCount="indefinite" />
        </line>
        
        <!-- 左侧边框 -->
        <line
          class="border-line border-left"
          x1="0"
          :y1="cornerSize"
          x2="0"
          :y2="height - cornerSize"
          stroke-dasharray="5,5"
        >
          <animate attributeName="stroke-dashoffset" from="0" to="10" dur="1s" repeatCount="indefinite" />
        </line>
      </g>
      
      <!-- 装饰小方块 -->
      <rect class="deco-rect deco-rect-1" :x="cornerSize + 10" y="0" width="4" height="4" />
      <rect class="deco-rect deco-rect-2" :x="width - cornerSize - 14" y="0" width="4" height="4" />
      <rect class="deco-rect deco-rect-3" x="0" :y="cornerSize + 10" width="4" height="4" />
      <rect class="deco-rect deco-rect-4" :x="width - 4" :y="cornerSize + 10" width="4" height="4" />
    </svg>
    
    <!-- Gradient 渐变样式 SVG -->
    <svg v-else-if="normalizedType === 'gradient'" class="border-svg-gradient" :width="width" :height="height">
      <defs>
        <linearGradient :id="`gradient-border-${uid}`" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" :stop-color="mergedColor[0]" stop-opacity="0.3" />
          <stop offset="100%" :stop-color="mergedColor[1]" stop-opacity="1" />
        </linearGradient>
      </defs>
      
      <polyline
        class="border-line-1"
        :stroke="`url(#gradient-border-${uid})`"
        :points="`0, ${height * 0.2} 0, 0 ${width * 0.2}, 0`"
      />
      <polyline
        class="border-line-2"
        :stroke="`url(#gradient-border-${uid})`"
        :points="`${width * 0.8}, 0 ${width}, 0 ${width}, ${height * 0.2}`"
      />
      <polyline
        class="border-line-3"
        :stroke="`url(#gradient-border-${uid})`"
        :points="`${width}, ${height * 0.8} ${width}, ${height} ${width * 0.8}, ${height}`"
      />
      <polyline
        class="border-line-4"
        :stroke="`url(#gradient-border-${uid})`"
        :points="`${width * 0.2}, ${height} 0, ${height} 0, ${height * 0.8}`"
      />
      
      <!-- 装饰点 -->
      <circle class="deco-circle" :cx="0" :cy="0" r="3" :fill="mergedColor[1]">
        <animate attributeName="r" values="3;5;3" dur="2s" repeatCount="indefinite" />
      </circle>
      <circle class="deco-circle" :cx="width" :cy="0" r="3" :fill="mergedColor[1]">
        <animate attributeName="r" values="3;5;3" dur="2s" begin="0.5s" repeatCount="indefinite" />
      </circle>
      <circle class="deco-circle" :cx="width" :cy="height" r="3" :fill="mergedColor[1]">
        <animate attributeName="r" values="3;5;3" dur="2s" begin="1s" repeatCount="indefinite" />
      </circle>
      <circle class="deco-circle" :cx="0" :cy="height" r="3" :fill="mergedColor[1]">
        <animate attributeName="r" values="3;5;3" dur="2s" begin="1.5s" repeatCount="indefinite" />
      </circle>
    </svg>
    
    <!-- Scan 扫描线样式 SVG -->
    <svg v-else-if="normalizedType === 'scan'" class="border-svg-scan" :width="width" :height="height">
      <defs>
        <linearGradient :id="`grad1-${uid}`" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" :stop-color="mergedColor[0]" stop-opacity="0" />
          <stop offset="50%" :stop-color="mergedColor[0]" stop-opacity="1" />
          <stop offset="100%" :stop-color="mergedColor[0]" stop-opacity="0" />
        </linearGradient>
        
        <radialGradient :id="`grad2-${uid}`">
          <stop offset="0%" :stop-color="mergedColor[1]" stop-opacity="1" />
          <stop offset="100%" :stop-color="mergedColor[1]" stop-opacity="0" />
        </radialGradient>
      </defs>
      
      <!-- 顶部装饰 -->
      <path
        class="top-decoration"
        :d="`M 0 0 L ${width} 0`"
        :stroke="`url(#grad1-${uid})`"
        stroke-width="2"
      />
      
      <!-- 底部装饰 -->
      <path
        class="bottom-decoration"
        :d="`M 0 ${height} L ${width} ${height}`"
        :stroke="`url(#grad1-${uid})`"
        stroke-width="2"
      />
      
      <!-- 左侧装饰 -->
      <path
        class="left-decoration"
        :d="`M 0 0 L 0 ${height}`"
        :stroke="mergedColor[0]"
        stroke-width="1"
        opacity="0.3"
      />
      
      <!-- 右侧装饰 -->
      <path
        class="right-decoration"
        :d="`M ${width} 0 L ${width} ${height}`"
        :stroke="mergedColor[0]"
        stroke-width="1"
        opacity="0.3"
      />
      
      <!-- 四角装饰 -->
      <g class="corner-decoration-13">
        <!-- 左上 -->
        <path
          :d="`M 0 ${cornerSize} L 0 0 L ${cornerSize} 0`"
          :stroke="mergedColor[1]"
          stroke-width="2"
          fill="none"
        />
        <circle :cx="0" :cy="0" r="2" :fill="mergedColor[1]" />
        
        <!-- 右上 -->
        <path
          :d="`M ${width - cornerSize} 0 L ${width} 0 L ${width} ${cornerSize}`"
          :stroke="mergedColor[1]"
          stroke-width="2"
          fill="none"
        />
        <circle :cx="width" :cy="0" r="2" :fill="mergedColor[1]" />
        
        <!-- 右下 -->
        <path
          :d="`M ${width} ${height - cornerSize} L ${width} ${height} L ${width - cornerSize} ${height}`"
          :stroke="mergedColor[1]"
          stroke-width="2"
          fill="none"
        />
        <circle :cx="width" :cy="height" r="2" :fill="mergedColor[1]" />
        
        <!-- 左下 -->
        <path
          :d="`M ${cornerSize} ${height} L 0 ${height} L 0 ${height - cornerSize}`"
          :stroke="mergedColor[1]"
          stroke-width="2"
          fill="none"
        />
        <circle :cx="0" :cy="height" r="2" :fill="mergedColor[1]" />
      </g>
      
      <!-- 扫描线 -->
      <line
        class="scan-line-h"
        x1="0"
        :y1="height / 2"
        :x2="width"
        :y2="height / 2"
        :stroke="`url(#grad1-${uid})`"
        stroke-width="1"
        opacity="0.5"
      >
        <animate attributeName="y1" :values="`0;${height};0`" dur="4s" repeatCount="indefinite" />
        <animate attributeName="y2" :values="`0;${height};0`" dur="4s" repeatCount="indefinite" />
      </line>
    </svg>
    
    <div class="border-box-content">
      <slot></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useSettingsStore } from '@/store'
import { ThemeEnum } from '@/enums/ThemeEnum'

interface Props {
  type?: 'default' | 'gradient' | 'scan'   // 保留旧名称作为别名
  variant?: 'primary' | 'success' | 'warning' | 'danger'
  cornerSize?: number
  showBorder?: boolean
  reverse?: boolean
  color?: string[]
  width?: number | string  // 自定义宽度
  height?: number | string  // 自定义高度
}

const props = withDefaults(defineProps<Props>(), {
  type: 'default',
  variant: 'primary',
  cornerSize: 20,
  showBorder: true,
  reverse: false
})

// 类型别名映射：将旧名称映射到新名称
const normalizedType = computed(() => {
  const typeMap: Record<string, 'default' | 'gradient' | 'scan'> = {
    'style8': 'gradient',
    'style13': 'scan',
    'default': 'default',
    'gradient': 'gradient',
    'scan': 'scan'
  }
  return typeMap[props.type] || 'default'
})

const settingsStore = useSettingsStore()
const isDark = computed(() => settingsStore.theme === ThemeEnum.DARK)

const containerRef = ref<HTMLElement>()
const autoWidth = ref(0)
const autoHeight = ref(0)
const uid = ref(`border-${Math.random().toString(36).substr(2, 9)}`)

// 计算实际使用的宽高：优先使用props，否则使用自动获取的尺寸
const width = computed(() => {
  if (props.width) {
    return typeof props.width === 'number' ? props.width : parseInt(props.width)
  }
  return autoWidth.value
})

const height = computed(() => {
  if (props.height) {
    return typeof props.height === 'number' ? props.height : parseInt(props.height)
  }
  return autoHeight.value
})

// 颜色配置
const defaultColor = computed(() => 
  isDark.value 
    ? ['#00d4ff', '#00ffff'] 
    : ['#409eff', '#66b1ff']
)

const mergedColor = computed(() => props.color || defaultColor.value)

const updateSize = () => {
  if (containerRef.value) {
    autoWidth.value = containerRef.value.offsetWidth
    autoHeight.value = containerRef.value.offsetHeight
  }
}

// ResizeObserver 实例
let resizeObserver: ResizeObserver | null = null

onMounted(() => {
  updateSize()
  
  // 使用 ResizeObserver 监听容器尺寸变化
  if (containerRef.value) {
    resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        if (entry.target === containerRef.value) {
          autoWidth.value = entry.contentRect.width
          autoHeight.value = entry.contentRect.height
        }
      }
    })
    resizeObserver.observe(containerRef.value)
  }
  
  // 监听窗口大小变化（作为备用）
  window.addEventListener('resize', updateSize)
  
  // 延迟更新尺寸，确保容器已渲染
  setTimeout(updateSize, 100)
})

onUnmounted(() => {
  // 清理 ResizeObserver
  if (resizeObserver && containerRef.value) {
    resizeObserver.unobserve(containerRef.value)
    resizeObserver.disconnect()
    resizeObserver = null
  }
  
  window.removeEventListener('resize', updateSize)
})
</script>

<style lang="scss" scoped>
.dv-border-box {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  
  // 扫描线效果
  .scan-line {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 2px;
    background: linear-gradient(90deg, 
      transparent, 
      var(--border-color), 
      transparent
    );
    opacity: 0.6;
    animation: scanning 3s linear infinite;
    z-index: 3;
    pointer-events: none;
  }
  
  // 背景网格
  .bg-grid {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: 
      linear-gradient(var(--border-color) 1px, transparent 1px),
      linear-gradient(90deg, var(--border-color) 1px, transparent 1px);
    background-size: 20px 20px;
    opacity: 0.05;
    z-index: 0;
    pointer-events: none;
  }
  
  .border-svg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 2;
    
    polyline, line, rect {
      fill: none;
      stroke-width: 2;
      stroke-linecap: round;
      stroke-linejoin: round;
    }
    
    .corner-main {
      stroke: var(--border-color);
      stroke-width: 2.5;
    }
    
    .corner-inner {
      stroke: var(--border-color);
      stroke-width: 1;
      opacity: 0.5;
    }
    
    .corner-dot {
      fill: var(--border-color);
      filter: drop-shadow(0 0 3px var(--glow-color));
    }
    
    .border-line {
      stroke: var(--border-color);
      opacity: 0.4;
      stroke-width: 1;
    }
    
    .deco-rect {
      fill: var(--border-color);
      opacity: 0.8;
      
      &.deco-rect-1 {
        animation: blink 2s ease-in-out infinite;
      }
      &.deco-rect-2 {
        animation: blink 2s ease-in-out 0.5s infinite;
      }
      &.deco-rect-3 {
        animation: blink 2s ease-in-out 1s infinite;
      }
      &.deco-rect-4 {
        animation: blink 2s ease-in-out 1.5s infinite;
      }
    }
  }
  
  .border-box-content {
    position: relative;
    width: 100%;
    height: 100%;
    z-index: 1;
    padding: 20px;
  }
  
  // 主题色变量
  &.border-box-primary {
    --border-color: #409eff;
    --glow-color: rgba(64, 158, 255, 0.5);
  }
  
  &.border-box-success {
    --border-color: #67c23a;
    --glow-color: rgba(103, 194, 58, 0.5);
  }
  
  &.border-box-warning {
    --border-color: #e6a23c;
    --glow-color: rgba(230, 162, 60, 0.5);
  }
  
  &.border-box-danger {
    --border-color: #f56c6c;
    --glow-color: rgba(245, 108, 108, 0.5);
  }
  
  // 暗黑主题
  &.is-dark {
    &.border-box-primary {
      --border-color: #00d4ff;
      --glow-color: rgba(0, 212, 255, 0.5);
    }
    
    &.border-box-success {
      --border-color: #00ff88;
      --glow-color: rgba(0, 255, 136, 0.5);
    }
    
    &.border-box-warning {
      --border-color: #ffaa00;
      --glow-color: rgba(255, 170, 0, 0.5);
    }
    
    &.border-box-danger {
      --border-color: #ff4466;
      --glow-color: rgba(255, 68, 102, 0.5);
    }
    
    .border-svg {
      .corner-main {
        filter: drop-shadow(0 0 5px var(--glow-color));
      }
    }
  }
  
  // Gradient 渐变样式
  &.border-type-gradient {
    background: linear-gradient(135deg, 
      rgba(255, 255, 255, 0.9) 0%, 
      rgba(249, 250, 251, 0.95) 100%
    );
    box-shadow: 
      0 2px 8px rgba(0, 0, 0, 0.08),
      0 1px 2px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    
    .border-svg-gradient {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      
      polyline {
        fill: none;
        stroke-width: 3;
        stroke-linecap: round;
        opacity: 0.8;
      }
      
      .deco-circle {
        opacity: 0.9;
      }
    }
    
    &.is-dark {
      background: linear-gradient(135deg, 
        rgba(10, 25, 41, 0.6) 0%, 
        rgba(26, 35, 50, 0.8) 100%
      );
      box-shadow: 
        0 0 20px rgba(0, 212, 255, 0.15),
        inset 0 0 30px rgba(0, 212, 255, 0.05);
      
      .border-svg-gradient {
        polyline {
          filter: drop-shadow(0 0 5px currentColor);
          stroke-width: 2.5;
        }
        
        .deco-circle {
          filter: drop-shadow(0 0 5px currentColor);
        }
      }
    }
    
    &.reverse {
      .border-svg-gradient {
        transform: rotateY(180deg);
      }
    }
  }
  
  // Scan 扫描线样式
  &.border-type-scan {
    background: linear-gradient(135deg, 
      rgba(255, 255, 255, 0.95) 0%, 
      rgba(250, 251, 252, 1) 100%
    );
    box-shadow: 
      0 4px 12px rgba(0, 0, 0, 0.08),
      0 2px 4px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    
    .border-svg-scan {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      
      path, line {
        stroke-linecap: round;
        stroke-width: 2.5;
        opacity: 0.7;
      }
      
      .corner-decoration-13 {
        path {
          animation: cornerGlow 2s ease-in-out infinite;
          stroke-width: 3;
          opacity: 0.85;
        }
        
        circle {
          animation: dotPulse 2s ease-in-out infinite;
          opacity: 0.9;
        }
      }
    }
    
    &.is-dark {
      background: linear-gradient(135deg, 
        rgba(10, 25, 41, 0.7) 0%, 
        rgba(26, 35, 50, 0.9) 100%
      );
      box-shadow: 
        0 0 25px rgba(0, 212, 255, 0.2),
        inset 0 0 40px rgba(0, 212, 255, 0.08);
      
      .border-svg-scan {
        path, line {
          filter: drop-shadow(0 0 6px currentColor);
          stroke-width: 2;
        }
      }
    }
  }
}

// 扫描线动画
@keyframes scanning {
  0% {
    transform: translateY(0);
    opacity: 0;
  }
  10% {
    opacity: 0.6;
  }
  90% {
    opacity: 0.6;
  }
  100% {
    transform: translateY(100vh);
    opacity: 0;
  }
}

// 闪烁动画
@keyframes blink {
  0%, 100% {
    opacity: 0.3;
  }
  50% {
    opacity: 1;
  }
}

// 角落发光动画
@keyframes cornerGlow {
  0%, 100% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
}

// 圆点脉冲动画
@keyframes dotPulse {
  0%, 100% {
    transform: scale(1);
    opacity: 0.8;
  }
  50% {
    transform: scale(1.5);
    opacity: 1;
  }
}
</style>
